---
name: useScript
rank: 14
tagline: Load and manage external JavaScript scripts with useScript.
sandboxId: usescript-dux91r
previewHeight: 300px
relatedHooks:
  - usefetch
---

import CodePreview from "../../components/CodePreview.astro";
import HookDescription from "../../components/HookDescription.astro";
import StaticCodeContainer from "../../components/StaticCodeContainer.astro";

<HookDescription name={frontmatter.name}>
  The useScript hook is useful for dynamically loading external JavaScript
  scripts into a React component. It manages the loading and status of the
  script, allowing you to conditionally render components or perform actions
  based on whether the script has been successfully loaded or encountered an
  error. The hook keeps track of the script’s status and provides this status as a return value. Additionally,
  it offers options to remove the script when the component is unmounted,
  ensuring proper cleanup.
</HookDescription>

<div class="reference">
  ### Parameters

  <div class="table-container">
  | Name             | Type   | Description |
  | ---------------- | ------ | ----------- |
  | src              | string | This is the URL source of the script to be loaded. |
  | options          | object | This is an optional configuration object provided when calling `useScript`. It currently accepts one property `removeOnUnmount` which when set to `true`, will remove the script tag from the document body on component unmount. |
  </div>

  ### Return Values

  <div class="table-container">
  | Name   | Type   | Description |
  | ------ | ------ | ----------- |
  | status | string | This represents the status of the script load, `loading`, `ready`, `error`, or `unknown`. An `unknown` script is one that previously exists in the document, but was not added via `useScript`.  |
  </div>
</div>

<CodePreview
  sandboxId={frontmatter.sandboxId}
  previewHeight={frontmatter.previewHeight}
/>

<StaticCodeContainer>

```jsx
import * as React from "react";
import { useScript } from "@uidotdev/usehooks";
import ScriptMeta from './ScriptMeta'

export default function App() {
  const status = useScript(
    `https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.js`,
    {
      removeOnUnmount: false,
    }
  );

  React.useEffect(() => {
    if (typeof window.$$ !== "undefined") {
      const id = document.id("moo");
      id.setStyle("background-color", "var(--green)");
    }
  }, [status]);

  const isReady = status === "ready";

  return (
    <section>
      <h1>useScript</h1>
      <p>
        <span id="moo" className={isReady ? "ready" : ""} />
        <label>Status: {status}</label>
      </p>
      {status === "ready" && (
        <ScriptMeta title="MooTools" status={status} meta={window.MooTools} />
      )}
    </section>
  );
}
```

</StaticCodeContainer>
